import React, { useState } from 'react';
import { useDropzone } from 'react-dropzone';
import JSZip from 'jszip';
import MenuButton from './Button';
import axios from 'axios';
import { json } from 'react-router-dom';

const FileUploader = ({loadResult, message}) => {
  const [files, setFiles] = useState([]);
  const [converted, setConverted] = useState(false)
  const [finalfile, setFinalFile] = useState(null)
  
  const onDrop = acceptedFiles => {
    setFiles(acceptedFiles);
  };

  
  function handleSend(){
    console.log(files)
    const formData = new FormData();
    files.forEach(file => {
      formData.append('files', file);
    });
    
    formData.append("text", message)
    var i = 0
    for(let item of files){
        formData.append(`files[${i}]`, files[i])
    }
    axios({
      method: 'post',
      url: 'http://localhost:8000/api/v1/emails',
      data: formData,
      headers: {
          'Accept': 'application/json',
          'Content-Type': 'multipart/form-data'
      },
  }).then((response)=>{

       if(response.status === 200) loadResult();
       else alert("Не удалось отправить запрос!")
  }
  )
}

  const {getRootProps, getInputProps} = useDropzone({onDrop});

  return (
    <div>
      <div {...getRootProps()} style={{border: '1px dashed black', padding: '20px'}}>
        <input {...getInputProps()} />
        <p>{files.length === 0? "Перетащите файлы сюда или кликните для выбора": `Выбрано ${files.length} файла(-ов)`}</p>
      </div>
      <MenuButton text={files.length === 0? "": "Отправить"} onClick={handleSend} disabled={files.length === 0? true:false}></MenuButton>
    </div>
  );
};

export default FileUploader;